--First, drop the stored procedure if it exists
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'disallow_entry')
    BEGIN
        PRINT 'Dropping Procedure disallow_entry'
        DROP PROCEDURE  disallow_entry
    END
    PRINT 'Creating Procedure disallow_entry'
GO
CREATE PROCEDURE disallow_entry
(
	@npa smallint,
	@nxx smallint,
	@xxxx smallint = null
)
AS
BEGIN
    /*
    Stored Procedure
    Name: disallow_entry
    Parameters:
        @npa smallint : The NPA of the ANI/Exchange to remove
        @nxx smallint : The NXX of the ANI/Exchange to remove
        @xxxx smallint : The XXXX value of the ANI to remove. Null if removing an exchange
    Return codes:
        0: Success
        1: One of the parameters is invalid
        2: The exchange/ANI does not exist
    */
    
    --Determine if any of the parameters are invalid.
    IF(@npa IS NULL
        OR @npa < 201
        OR @npa > 999
        OR @nxx IS NULL
        OR @nxx < 200
        OR @nxx > 999
        OR (@xxxx IS NOT NULL AND (@xxxx < 201 OR @xxxx > 9999)))
    BEGIN
        --Return an error code for invalid parameters
        RETURN 1
    END
    
    --If this is an ANI
    IF(@xxxx IS NOT NULL)
    BEGIN
        --All validation checks have passed, so remove the ANI
        DELETE FROM Config.AllowedANI 
        WHERE NPA = @npa
        AND NXX = @nxx
        AND XXXX = @xxxx
    END
    ELSE
    BEGIN
        --All validation checks have passed, so remove the exchange
        DELETE FROM Config.AllowedNPANXX 
        WHERE NPA = @npa
        AND NXX = @nxx
    END
    
    --Return with an error code if nothing was there to remove
    IF(@@RowCount IS NULL OR @@RowCount <> 1)
    BEGIN
        RETURN 2
    END
    
    --Return successfully
    RETURN 0
END